package com.jmemoir.mq.rabbitmq.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * RabbitMQ 消息确认回调
 *
 * @author Tellsea
 * @date 2023/9/6
 */
@Slf4j
@Component
public class MessageConfirmCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 只要生产者往交换机发送消息，都会该触发
     *
     * @param correlationData correlation data for the callback.
     * @param ack             true for ack, false for nack
     * @param cause           An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("交换机收到消息成功：" + correlationData.getId());
        } else {
            System.out.println("交换机收到消息失败：" + correlationData.getId() + "原因：" + cause);
        }
    }

    /**
     * 消息成功发送到 exchange，但没有路由到 queue
     *
     * @param returned the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        Message message = returned.getMessage();
        // 判断是否是延迟消息
        Integer delayTime = message.getMessageProperties().getHeader("x-delay");
        if (delayTime != null && delayTime > 0) {
            return;
        }
        log.error("消息发送到队列失败，响应码：{}, 失败原因：{}, 交换机: {}, 路由key：{}, 消息: {}",
                returned.getReplyCode(), returned.getReplyText(), returned.getExchange(), returned.getRoutingKey(), message.toString());
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        // 此方法已经过时了，重写一下不做操作，否则延迟队列会报错抛出 UnsupportedOperationException，可查看源码
    }
}
